package com.fhc.base

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Configuration
import android.os.LocaleList
import androidx.annotation.StringRes
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.edit
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import timber.log.Timber
import java.util.Locale

object LocalManager {
    private const val APP_PREFS = "AppPreferences"
    private const val PREFS_LANGUAGE = "app_language"
    private var _currentLocale  = MutableStateFlow<Locale>(Locale.getDefault())
    val currentLocale: StateFlow<Locale> = _currentLocale.asStateFlow()
    private var _isSystemLocale  = MutableStateFlow<Boolean>(true)
    val isSystemLocale: StateFlow<Boolean> = _isSystemLocale.asStateFlow()
    fun initialize(context: Context) {
        _currentLocale.value = loadAppLocale(context)
//        if(_currentLocale.value.language  != Locale.ENGLISH.language && _currentLocale.value.language != Locale.JAPANESE.language){
//            setAppLocale(context,  Locale.ENGLISH.language)
//        }else{
////            updateConfiguration(context, _currentLocale.value)
//        }
    }

    fun setAppLocale(context: Context, languageTag: String) {
        if(languageTag.isEmpty()) {
            _isSystemLocale.value = true
            context.getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE)
                .edit {
                    remove(PREFS_LANGUAGE)
                    apply()
                }
            _currentLocale.value = Locale.getDefault()
            return
        }
        _isSystemLocale.value = false
        val newLocale = Locale.forLanguageTag(languageTag).takeIf { it != _currentLocale.value }
            ?: return
        saveAppLocale(context, newLocale)

        _currentLocale.value = newLocale
    }

    @SuppressLint("UseKtx")
    private fun saveAppLocale(context: Context, locale: Locale) {
        context.getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE)
            .edit {
                putString(PREFS_LANGUAGE, locale.toLanguageTag())
            }
    }

    private fun loadAppLocale(context: Context): Locale {
        val str = context.getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE)
            .getString(PREFS_LANGUAGE, "")
        if(!str.isNullOrEmpty()) {
            _isSystemLocale.value = false
            return Locale.forLanguageTag(str)
        }
        _isSystemLocale.value = true
        return Locale.getDefault()
    }

    val LocalAppLanguage = compositionLocalOf { _currentLocale.value }


    val LocalDynamicContext = compositionLocalOf<Context?> {
        null
    }

    @Composable
    fun LanguageProvider(
        content: @Composable () -> Unit
    ) {
//        if(isSystemLocale.collectAsState().value){
//            content()
//        }else{

            val context = LocalContext.current
            val currentLocale = currentLocale.collectAsStateWithLifecycle()

            val dynamicContext = remember(currentLocale.value) {
                val config = Configuration().apply {
                    setLocale(currentLocale.value)
                    setLocales(LocaleList(currentLocale.value))
                }
                context.createConfigurationContext(config)
            }

            Timber.i(">>>LanguageProvider  LanguageProvider      ${currentLocale.value.language}")
            DisposableEffect(Unit) {
                onDispose {
                    // 清理逻辑
                }
            }

            CompositionLocalProvider(
                LocalDynamicContext provides dynamicContext,
                LocalAppLanguage provides currentLocale.value,
            ){
                Timber.i(">>>CompositionLocalProvider  CompositionLocalProvider      ${currentLocale.value.language}")
                content()
            }
//        }
    }
    @Composable
    fun stringResource(@StringRes id: Int, vararg formatArgs: Any): String {
        if(isSystemLocale.collectAsState().value){
            return LocalContext.current.getString(id, *formatArgs)
        }else{
            // 直接使用 LocalDynamicContext，如果未提供则会抛出错误
            // 为了确保应用正常运行，我们应确保始终通过 LanguageProvider 提供上下文
            var context = LocalDynamicContext.current
            if(context == null)  context = LocalContext.current
            return remember(id, *formatArgs, context) {
                context.getString(id, *formatArgs)
            }
        }
    }

}